package org.template.dao;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.template.dao.iter.RedisDelegator;

import redis.clients.jedis.Jedis;

@Repository
public class StringRedisDao extends BaseRedisDao {

	public String getString(final String key) {

		return run(new RedisDelegator<String>() {
			@Override
			public String execute(Jedis redis) {
				return redis.get(key);
			}
		});

	}

	public boolean setNXValue(final String key, final String value, final int expireSeconds) {

		return run(new RedisDelegator<Boolean>() {
			@Override
			public Boolean execute(Jedis redis) {
				Long result = redis.setnx(key, value);
				if (1 != result)
					return false;
				if (0 != expireSeconds)
					redis.expire(key, expireSeconds);
				return true;
			}
		});
	}

	public boolean setValueForse(final String key, final String value, final int expireSeconds) {
		return run(new RedisDelegator<Boolean>() {
			@Override
			public Boolean execute(Jedis redis) {
				String result = redis.set(key, value);
				if (!"OK".equalsIgnoreCase(result))
					return false;
				if (0 != expireSeconds)
					redis.expire(key, expireSeconds);
				return true;
			}
		});
	}

	public long incrValue(String key) {
		return incrValueBy(key, 1);

	}

	public List<String> batchGetString(final String... key) {

		return run(new RedisDelegator<List<String>>() {
			@Override
			public List<String> execute(Jedis redis) {
				return redis.mget(key);
			}
		});
	}

	public long incrValueBy(final String key, final int add) {

		return run(new RedisDelegator<Long>() {
			@Override
			public Long execute(Jedis redis) {
				return redis.incrBy(key, add);
			}
		});

	}

}
